import gradio as gr
import os
import json
from pathlib import Path

def get_project_folders():
    """获取data目录下的文件夹名称"""
    data_path = Path(__file__).parent.parent / "data"
    if data_path.exists():
        folders = [item.name for item in data_path.iterdir() if item.is_dir()]
        return folders if folders else ["暂无项目"]
    return ["暂无项目"]

def save_config(project_name):
    """保存配置到config文件夹"""
    config_path = Path(__file__).parent.parent / "config"
    config_path.mkdir(exist_ok=True)
    
    config_file = config_path / "app_config.json"
    config_data = {
        "selected_project": project_name
    }
    
    with open(config_file, 'w', encoding='utf-8') as f:
        json.dump(config_data, f, ensure_ascii=False, indent=2)

def load_config():
    """从config文件夹加载配置"""
    config_file = Path(__file__).parent.parent / "config" / "app_config.json"
    
    if config_file.exists():
        try:
            with open(config_file, 'r', encoding='utf-8') as f:
                config_data = json.load(f)
                return config_data.get("selected_project", None)
        except (json.JSONDecodeError, FileNotFoundError):
            return None
    return None

def get_project_progress(project_name):
    """获取项目进度信息（目前返回静态数据）"""
    if project_name == "暂无项目":
        return {
            "切分章节": 0,
            "已清洗文本": "0/0",
            "抽取角色": "0/0", 
            "抽取其他特征": "0/0"
        }
    
    # 这里是静态数据，后续可以根据实际项目文件来动态获取
    chapter_count = 33  # 示例数据
    cleaned_count = 11  # 示例数据
    character_count = 11  # 示例数据
    feature_count = 33  # 示例数据
    
    return {
        "切分章节": chapter_count,
        "已清洗文本": f"{cleaned_count}/{chapter_count}",
        "抽取角色": f"{character_count}/{chapter_count}",
        "抽取其他特征": f"{feature_count}/{chapter_count}"
    }

def create_interface():
    """创建Gradio界面"""
    
    # 获取项目文件夹列表
    project_folders = get_project_folders()
    
    # 加载上次选中的项目
    saved_project = load_config()
    default_project = saved_project if saved_project in project_folders else (project_folders[0] if project_folders else None)
    
    with gr.Blocks(title="story2video") as demo:
        # 页面标题
        gr.Markdown("# story2video", elem_classes=["title"])
        
        # Tab栏
        with gr.Tabs():
            with gr.TabItem("文本处理"):
                # 信息展示模块
                with gr.Group():
                    gr.Markdown("### 项目信息")
                    
                    # 项目名称显示
                    project_name_display = gr.Textbox(
                        label="名称",
                        value=default_project or "暂无项目",
                        interactive=False,
                        container=True
                    )
                    
                    # 进度信息显示
                    with gr.Row():
                        chapter_count_display = gr.Textbox(
                            label="切分章节",
                            value="0",
                            interactive=False,
                            container=True
                        )
                        cleaned_text_display = gr.Textbox(
                            label="已清洗文本",
                            value="0/0",
                            interactive=False,
                            container=True
                        )
                    
                    with gr.Row():
                        character_extract_display = gr.Textbox(
                            label="抽取角色",
                            value="0/0",
                            interactive=False,
                            container=True
                        )
                        feature_extract_display = gr.Textbox(
                            label="抽取其他特征",
                            value="0/0",
                            interactive=False,
                            container=True
                        )
                
                # 第一步区域：选择项目
                with gr.Group():
                    gr.Markdown("### 第一步：选择项目")
                    project_dropdown = gr.Dropdown(
                        choices=project_folders,
                        label="项目选择",
                        value=default_project,
                        interactive=True,
                        info="选择要处理的项目文件夹"
                    )
                    
                    # 刷新按钮，用于重新加载项目列表
                    refresh_btn = gr.Button("刷新项目列表", variant="secondary", size="sm")
                    
                    def refresh_projects():
                        updated_folders = get_project_folders()
                        return gr.Dropdown(choices=updated_folders, value=updated_folders[0] if updated_folders else None)
                    
                    def update_project_info(selected_project):
                        """更新项目信息显示"""
                        if selected_project:
                            # 保存配置
                            save_config(selected_project)
                            
                            # 获取项目进度
                            progress = get_project_progress(selected_project)
                            
                            # 处理颜色显示逻辑
                            def format_progress_text(text, total_count):
                                if "/" in text:
                                    current, total = text.split("/")
                                    if current == total and int(total) > 0:
                                        return f"<span style='color: green;'>{text}</span>"
                                return text
                            
                            chapter_count = str(progress["切分章节"])
                            cleaned_text = format_progress_text(progress["已清洗文本"], progress["切分章节"])
                            character_extract = format_progress_text(progress["抽取角色"], progress["切分章节"])
                            feature_extract = format_progress_text(progress["抽取其他特征"], progress["切分章节"])
                            
                            return (
                                selected_project,
                                chapter_count,
                                cleaned_text,
                                character_extract,
                                feature_extract
                            )
                        else:
                            return "暂无项目", "0", "0/0", "0/0", "0/0"
                    
                    # 绑定事件
                    refresh_btn.click(
                        refresh_projects,
                        outputs=project_dropdown
                    )
                    
                    project_dropdown.change(
                        update_project_info,
                        inputs=project_dropdown,
                        outputs=[
                            project_name_display,
                            chapter_count_display,
                            cleaned_text_display,
                            character_extract_display,
                            feature_extract_display
                        ]
                    )
                    
                    # 初始化显示
                    if default_project:
                        progress = get_project_progress(default_project)
                        project_name_display.value = default_project
                        chapter_count_display.value = str(progress["切分章节"])
                        cleaned_text_display.value = progress["已清洗文本"]
                        character_extract_display.value = progress["抽取角色"]
                        feature_extract_display.value = progress["抽取其他特征"]
    
    return demo

if __name__ == "__main__":
    # 创建并启动界面
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7861,
        share=False,
        debug=True
    )